package backend

import (
	"lanmon/internal/config"

	"github.com/pkg/errors"
)

type Backend struct {
	MDns       *Mdns
	MQTTServer *MqttServer
	MQTTClient *MqttClient
	HTTPServer *HttpServer
}

var lanBackend *Backend

func isLaunchServer(conf *config.Config) bool {
	return conf.General.LaunchServer != 0
}

func Setup(conf *config.Config) error {
	var mdns *Mdns
	var mqttServer *MqttServer
	var mqttClient *MqttClient
	var httpServer *HttpServer
	var err error

	if isLaunchServer(conf) { // server
		if mdns, err = setupMdnsServer(conf); err != nil {
			return errors.Wrap(err, "fail to setup mdns server")
		}
		if mqttServer, err = setupMqttServer(conf); err != nil {
			return errors.Wrap(err, "fail to setup mqtt server")
		}
		if httpServer, err = setupHttpServer(conf); err != nil {
			return errors.Wrap(err, "fail to setup http server")
		}
	} else {
		if mdns, err = setupMdnsClient(conf); err != nil {
			return errors.Wrap(err, "fail to setup mdns client")
		}
		if mqttClient, err = setupMqttClient(conf); err != nil {
			return errors.Wrap(err, "fail to setup mqtt client")
		}
	}

	lanBackend = &Backend{
		MDns:       mdns,
		MQTTServer: mqttServer,
		MQTTClient: mqttClient,
		HTTPServer: httpServer,
	}

	return nil
}

func Cleanup(conf *config.Config) error {
	if isLaunchServer(conf) {
		lanBackend.MDns.closeMdnsServer()
		lanBackend.MQTTServer.died()
		return nil
	}

	lanBackend.MDns.closeMdnsClient()
	lanBackend.MQTTClient.disconnect()
	return nil
}
